package fractal.filter;

public class SpotlightFilter extends FractalFilter
{
	private double factor;
	double contrast = 1.8;
	int rmeans, gmeans, bmeans;

	int centerX, centerY;
	double maxDistance;

	public SpotlightFilter()
	{
		factor = 1.2;
	}
	public void setFactor(int factor)
	{
		this.factor = factor;
	}

	private double dotDistance(int centerX, int centerY, int px, int py)
	{
		double xx = (centerX - px) * (centerX - px);
		double yy = (centerY - py) * (centerY - py);
		return (int) Math.sqrt(xx + yy);
	}

	@Override
	protected void initFilter()
	{
		centerX = width / 2;
		centerY = height / 2;
		maxDistance = Math.sqrt(centerX * centerX + centerY * centerY);
		int tr = 0, tg = 0, tb = 0;
		double redSum = 0, greenSum = 0, blueSum = 0;
		double total = width * height;
		for (int i = 0; i < total; i++)
		{
			tr = (inPixels[i] >> 16) & 0xff;
			tg = (inPixels[i] >> 8) & 0xff;
			tb = inPixels[i] & 0xff;
			redSum += tr;
			greenSum += tg;
			blueSum += tb;
		}
		rmeans = (int) (redSum / total);
		gmeans = (int) (greenSum / total);
		bmeans = (int) (blueSum / total);
	}
	@Override
	protected int calculatePixel(int i)
	{
		int ta = 0, tr = 0, tg = 0, tb = 0;
		ta = (inPixels[i] >> 24) & 0xff;
		tr = (inPixels[i] >> 16) & 0xff;
		tg = (inPixels[i] >> 8) & 0xff;
		tb = inPixels[i] & 0xff;

		tr -= rmeans;
		tg -= gmeans;
		tb -= bmeans;

		tr = (int) (tr * contrast + rmeans);
		tg = (int) (tg * contrast + gmeans);
		tb = (int) (tb * contrast + bmeans);

		double scale = (1.0
				- dotDistance(centerX, centerY, i % width, i / width)
						/ maxDistance)
				* factor;
		tr = (int) (scale * tr);
		tg = (int) (scale * tg);
		tb = (int) (scale * tb);
		return (ta << 24) | (clamp(tr) << 16) | (clamp(tg) << 8) | clamp(tb);
	}
}
